/*
Copyright 2011 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.google.rsm.core;

/**
 * Factory methods for new instances of {@link EventType}.
 *
 * @author arunabhaghosh@google.com (Arunabha Ghosh)
 */
public class EventTypes {
  /** Cannot instantiate. */
  private EventTypes() {
  }

  /**
   * Create a new {@code EventType} for the given implementation of
   * {@code Event}. This is intended to be used in combination with
   * {@code ClassEvent}.
   *
   * <p>The returned {@code EventType} implements {@code #toString}
   * by stripping the package name from the given class name.
   *
   * <p>It is not legal to use this with anonymous inner classes.
   * Instead, use an {@code InstanceEvent}.
   *
   * @see Event
   * @see EventType
   * @see ClassEvent
   * @see InstanceEvent
   *
   * @param klass the class of the {@code Event} implementation
   * @return a new {@code EventType} for given class
   */
  public static EventType create(final Class<? extends Event> klass) {
    return new EventType() {
      final String name;

      { name = generateName(klass); }

      @Override
      public String toString() {
        return name;
      }
    };
  }

  /**
   * Generate a string name for the given class.  This is done by
   * stripping the package name from the return value of
   * {@link Class#getCanonicalName}.
   */
  private static String generateName(Class<? extends Event> klass) {
    if (klass.getSimpleName().isEmpty()) {
      throw new IllegalArgumentException(
          String.format("%s is an anonymous inner class. "
              + "Use InstanceEvent instead.",
              klass.getName()));
    }

    String name = klass.getName();
    String canonical = klass.getCanonicalName();
    return canonical.substring(name.lastIndexOf(".") + 1);
  }
}
